<template>
  <div class="nrs-survey">
    <div class="header">
      <h1>{{ nrsConfig.title }}</h1>
      <p class="subtitle">{{ nrsConfig.subtitle }}</p>
      <div class="header-actions">
        <button @click="goToHome" class="home-btn">
          <span class="home-icon">🏠</span> {{ nrsConfig.buttons.home }}
        </button>
        <button @click="showSettings = true" class="settings-btn">
          <span class="settings-icon">⚙️</span> {{ nrsConfig.buttons.settings }}
        </button>
      </div>
    </div>

    <!-- 设置页面 -->
    <div class="settings-modal" v-if="showSettings">
      <div class="settings-content">
        <div class="settings-header">
          <h2>{{ nrsConfig.settings.title }}</h2>
          <button @click="closeSettings" class="close-btn">×</button>
        </div>

        <div class="settings-form">
          <div class="form-group">
            <label>问答编号：<span class="required">*</span></label>
            <input type="text" v-model="recorderInfo.surveyId" placeholder="请输入问答编号（用于区分不同组的问卷）"
              maxlength="20">
            <p class="field-hint">编号用于区分不同组的问卷，建议使用如：NRS001、PAIN_A等格式</p>
          </div>

          <div class="form-group">
            <label>记录人姓名：<span class="required">*</span></label>
            <input type="text" v-model="recorderInfo.name" placeholder="请输入记录人姓名" maxlength="50">
          </div>

          <div class="form-group">
            <label>职务/身份：<span class="required">*</span></label>
            <input type="text" v-model="recorderInfo.position" placeholder="请输入职务或身份" maxlength="50">
          </div>

          <div class="form-group">
            <label>所属机构：</label>
            <input type="text" v-model="recorderInfo.institution" placeholder="请输入所属机构（可选）" maxlength="100">
          </div>

          <div class="form-group">
            <label>联系方式：</label>
            <input type="text" v-model="recorderInfo.contact" placeholder="请输入联系方式（可选）" maxlength="50">
          </div>

          <div class="form-group">
            <label>默认备注：</label>
            <textarea v-model="recorderInfo.defaultRemarks" placeholder="设置默认备注信息，将自动填入每次评估的备注栏（可选）"
              rows="3" maxlength="200"></textarea>
          </div>
        </div>

        <div class="settings-actions">
          <button @click="saveRecorderInfo" class="save-settings-btn">保存设置</button>
          <button @click="closeSettings" class="cancel-btn">{{ nrsConfig.buttons.cancel }}</button>
        </div>
      </div>
    </div>

    <!-- 导出页面 -->
    <div class="export-modal" v-if="showExport">
      <div class="export-content">
        <div class="export-header">
          <h2>{{ nrsConfig.export.title }}</h2>
          <button @click="closeExport" class="close-btn">×</button>
        </div>

        <div class="export-form">
          <div class="export-info">
            <p><strong>当前问答编号：</strong>{{ recorderInfo.surveyId }}</p>
            <p><strong>导出说明：</strong>将从服务器打包当前编号的所有NRS疼痛评估数据</p>
          </div>

          <div class="form-group">
            <label>导出密码：<span class="required">*</span></label>
            <input type="password" v-model="exportPassword" placeholder="请输入导出密码" @keyup.enter="exportData">
            <p class="field-hint">{{ nrsConfig.messages.passwordHint }}</p>
          </div>

          <div class="export-options">
            <div class="form-group">
              <label>
                <input type="checkbox" v-model="exportOptions.includeRawData">
                包含原始评估数据
              </label>
            </div>
            <div class="form-group">
              <label>
                <input type="checkbox" v-model="exportOptions.includeStatistics">
                包含统计分析
              </label>
            </div>
          </div>
        </div>

        <div class="export-actions">
          <button @click="exportData" class="export-confirm-btn" :disabled="!exportPassword || isExporting">
            <span v-if="!isExporting">导出压缩包</span>
            <span v-else>导出中...</span>
          </button>
          <button @click="closeExport" class="cancel-btn">{{ nrsConfig.buttons.cancel }}</button>
        </div>
      </div>
    </div>

    <!-- 记录人信息显示 -->
    <div class="recorder-info-display" v-if="recorderInfo.name && !showSettings && !showResult && !showExport">
      <div class="recorder-card">
        <div class="recorder-main-info">
          <h3>问答编号：{{ recorderInfo.surveyId }}</h3>
          <p>记录人：{{ recorderInfo.name }} | {{ recorderInfo.position }}</p>
          <p v-if="recorderInfo.institution">{{ recorderInfo.institution }}</p>
        </div>
        <div class="recorder-actions">
          <button @click="showSettings = true" class="edit-recorder-btn">编辑</button>
          <button @click="showExportDialog" class="export-btn">{{ nrsConfig.buttons.export }}</button>
        </div>
      </div>
    </div>

    <!-- 问卷表单 -->
    <div class="survey-form" v-if="!showResult && !showSettings && !showExport">
      <!-- 基本信息 -->
      <div class="section">
        <h2>{{ nrsConfig.sections.basicInfo.title }}</h2>
        <div class="form-grid">
          <div class="form-group" v-for="field in nrsConfig.sections.basicInfo.fields" :key="field.name">
            <label>{{ field.label }}{{ field.required ? '：' : '：' }}<span v-if="field.required" class="required">*</span></label>
            
            <!-- 文本输入 -->
            <input v-if="field.type === 'text' || field.type === 'tel'" 
              :type="field.type" 
              v-model="formData[field.name]" 
              :placeholder="field.placeholder"
              :maxlength="field.maxlength">
            
            <!-- 数字输入 -->
            <input v-else-if="field.type === 'number'" 
              type="number" 
              v-model.number="formData[field.name]" 
              :placeholder="field.placeholder"
              :min="field.min"
              :max="field.max">
            
            <!-- 日期时间输入 -->
            <input v-else-if="field.type === 'datetime-local'" 
              type="datetime-local" 
              v-model="formData[field.name]">
            
            <!-- 文本域 -->
            <textarea v-else-if="field.type === 'textarea'" 
              v-model="formData[field.name]" 
              :placeholder="field.placeholder"
              :rows="field.rows"
              :maxlength="field.maxlength"></textarea>
            
            <!-- 单选按钮 -->
            <div v-else-if="field.type === 'radio'" class="radio-group">
              <label v-for="option in field.options" :key="option.value">
                <input type="radio" v-model="formData[field.name]" :value="option.value"> {{ option.label }}
              </label>
            </div>
          </div>
        </div>
      </div>

      <!-- NRS疼痛评估 -->
      <div class="section">
        <h2>{{ nrsConfig.sections.assessment.title }}</h2>
        <p class="assessment-description">{{ nrsConfig.sections.assessment.description }}</p>
        <p class="assessment-note">{{ nrsConfig.sections.assessment.note }}</p>

        <div class="question-item" v-for="question in nrsConfig.sections.assessment.questions" :key="question.id">
          <h4>{{ question.title }}</h4>
          <p class="question-desc">{{ question.description }}</p>

          <!-- NRS评分量表 -->
          <div v-if="question.type === 'nrs_scale'" class="nrs-scale">
            <div class="nrs-labels">
              <span class="nrs-label-left">无疼痛</span>
              <span class="nrs-label-right">最剧烈疼痛</span>
            </div>
            <div class="nrs-options">
              <label v-for="score in 11" :key="score-1" class="nrs-option">
                <input type="radio" v-model.number="formData[question.field]" :value="score-1">
                <span class="nrs-number">{{ score-1 }}</span>
              </label>
            </div>
          </div>

          <!-- 单选题 -->
          <div v-else-if="question.type === 'radio'" class="radio-group">
            <label v-for="option in question.options" :key="option.value">
              <input type="radio" v-model="formData[question.field]" :value="option.value"> {{ option.label }}
            </label>
          </div>

          <!-- 多选题 -->
          <div v-else-if="question.type === 'checkbox'" class="checkbox-group">
            <label v-for="option in question.options" :key="option.value">
              <input type="checkbox" :value="option.value" v-model="formData[question.field]"> {{ option.label }}
            </label>
          </div>

          <!-- 文本域 -->
          <textarea v-else-if="question.type === 'textarea'" 
            v-model="formData[question.field]" 
            :placeholder="question.placeholder"
            :rows="question.rows"></textarea>
        </div>
      </div>

      <!-- 提交按钮 -->
      <div class="form-actions">
        <button @click="submitAssessment" class="submit-btn" :disabled="!isFormValid">
          {{ nrsConfig.buttons.submit }}
        </button>
      </div>
    </div>

    <!-- 评估结果 -->
    <div class="result-section" v-if="showResult">
      <div class="result-header">
        <h2>{{ nrsConfig.result.title }}</h2>
        <div class="result-actions">
          <button @click="showExportDialog" class="export-btn">{{ nrsConfig.buttons.export }}</button>
          <button @click="saveToBackend" class="save-btn" :disabled="isSaving">
            {{ isSaving ? nrsConfig.buttons.saving : nrsConfig.buttons.save }}
          </button>
          <button @click="resetForm" class="reset-btn">{{ nrsConfig.buttons.reset }}</button>
        </div>
      </div>

      <div class="result-content">
        <!-- 疼痛等级 -->
        <div class="pain-level-card" :style="{ borderColor: result.painLevelColor }">
          <h3>{{ nrsConfig.result.painLevel }}</h3>
          <div class="pain-level-info">
            <span class="pain-level-name" :style="{ color: result.painLevelColor }">{{ result.painLevel }}</span>
            <span class="pain-level-range">({{ result.painLevelRange }})</span>
          </div>
          <p class="pain-level-desc">{{ result.description }}</p>
        </div>

        <!-- 疼痛评分详情 -->
        <div class="pain-scores">
          <h4>疼痛评分详情：</h4>
          <div class="score-grid">
            <div class="score-item">
              <span class="score-name">{{ nrsConfig.result.currentPain }}</span>
              <span class="score-value">{{ result.currentPain }}/10</span>
            </div>
            <div class="score-item">
              <span class="score-name">{{ nrsConfig.result.worstPain }}</span>
              <span class="score-value">{{ result.worstPain24h }}/10</span>
            </div>
            <div class="score-item">
              <span class="score-name">{{ nrsConfig.result.leastPain }}</span>
              <span class="score-value">{{ result.leastPain24h }}/10</span>
            </div>
            <div class="score-item">
              <span class="score-name">{{ nrsConfig.result.averagePain }}</span>
              <span class="score-value">{{ result.averagePain24h }}/10</span>
            </div>
            <div class="score-item">
              <span class="score-name">{{ nrsConfig.result.restPain }}</span>
              <span class="score-value">{{ result.restPain }}/10</span>
            </div>
            <div class="score-item">
              <span class="score-name">{{ nrsConfig.result.activityPain }}</span>
              <span class="score-value">{{ result.activityPain }}/10</span>
            </div>
            <div class="score-item">
              <span class="score-name">{{ nrsConfig.result.functionalImpact }}</span>
              <span class="score-value">{{ result.functionalImpact }}/10</span>
            </div>
          </div>
        </div>

        <!-- 疼痛特征 -->
        <div class="pain-characteristics" v-if="result.painLocation || result.painCharacter.length > 0 || result.painDuration">
          <h4>疼痛特征：</h4>
          <div v-if="result.painLocation" class="characteristic-item">
            <strong>疼痛部位：</strong>
            <span>{{ result.painLocation }}</span>
          </div>
          <div v-if="result.painCharacter.length > 0" class="characteristic-item">
            <strong>疼痛性质：</strong>
            <span>{{ getPainCharacterLabels(result.painCharacter) }}</span>
          </div>
          <div v-if="result.painDuration" class="characteristic-item">
            <strong>疼痛持续时间：</strong>
            <span>{{ getPainDurationLabel(result.painDuration) }}</span>
          </div>
        </div>

        <!-- 相关因素 -->
        <div class="pain-factors" v-if="result.painTriggers || result.painRelief">
          <h4>相关因素：</h4>
          <div v-if="result.painTriggers" class="factor-item">
            <strong>诱发因素：</strong>
            <p>{{ result.painTriggers }}</p>
          </div>
          <div v-if="result.painRelief" class="factor-item">
            <strong>缓解因素：</strong>
            <p>{{ result.painRelief }}</p>
          </div>
        </div>

        <!-- 建议措施 -->
        <div class="recommendations" v-if="result.recommendations.length > 0">
          <h4>{{ nrsConfig.result.recommendations }}：</h4>
          <ul>
            <li v-for="(rec, index) in result.recommendations" :key="index">{{ rec }}</li>
          </ul>
        </div>

        <!-- 评分说明 -->
        <div class="explanation">
          <h4>{{ nrsConfig.result.explanation.title }}：</h4>
          <ul>
            <li v-for="item in nrsConfig.result.explanation.items" :key="item">{{ item }}</li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { nrsConfig } from '@/config/nrsConfig.js';
import { calculateNRSAssessment, validateNRSForm } from '@/config/nrsLogic.js';

export default {
  name: 'NRSSurvey',
  mounted() {
    // 自动设置当前时间
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    this.formData.recordTime = `${year}-${month}-${day}T${hours}:${minutes}`;

    // 加载记录人信息
    this.loadRecorderInfo();
  },
  data() {
    return {
      nrsConfig,
      showResult: false,
      showSettings: false,
      showExport: false,
      isExporting: false,
      isSaving: false,
      exportPassword: '',
      // 记录人信息（设置）
      recorderInfo: {
        surveyId: '',
        name: '',
        position: '',
        institution: '',
        contact: '',
        defaultRemarks: ''
      },
      // 导出选项
      exportOptions: nrsConfig.exportOptions,
      // 问卷表单数据
      formData: {
        // 被评估人信息
        patientName: '',
        age: null,
        gender: '',
        diagnosis: '',
        phone: '',
        recordTime: '',
        remarks: '',
        // NRS疼痛评估项目
        currentPain: null,
        worstPain24h: null,
        leastPain24h: null,
        averagePain24h: null,
        restPain: null,
        activityPain: null,
        functionalImpact: null,
        painLocation: '',
        painCharacter: [],
        painDuration: '',
        painTriggers: '',
        painRelief: ''
      },
      result: {
        currentPain: 0,
        worstPain24h: 0,
        leastPain24h: 0,
        averagePain24h: 0,
        restPain: 0,
        activityPain: 0,
        functionalImpact: 0,
        maxPainScore: 0,
        painLocation: '',
        painCharacter: [],
        painDuration: '',
        painTriggers: '',
        painRelief: '',
        painLevel: '',
        painLevelColor: '',
        painLevelRange: '',
        description: '',
        recommendations: []
      }
    }
  },
  computed: {
    isFormValid() {
      const validation = validateNRSForm(this.formData);
      // 个人信息字段已改为选填，不再进行必填验证
      return validation.isValid && this.recorderInfo.surveyId && this.recorderInfo.name && this.recorderInfo.position;
    }
  },
  methods: {
    // 页面导航
    goToHome() {
      this.$router.push('/');
    },

    // 设置相关方法
    closeSettings() {
      this.showSettings = false;
    },

    saveRecorderInfo() {
      // 验证必填字段
      if (!this.recorderInfo.surveyId || !this.recorderInfo.name || !this.recorderInfo.position) {
        alert('请填写所有必填信息（问答编号、记录人姓名、职务/身份）！');
        return;
      }

      // 保存到本地存储
      localStorage.setItem('nrs_recorderInfo', JSON.stringify(this.recorderInfo));
      
      // 如果有默认备注，设置到表单中
      if (this.recorderInfo.defaultRemarks && !this.formData.remarks) {
        this.formData.remarks = this.recorderInfo.defaultRemarks;
      }

      this.showSettings = false;
      alert(nrsConfig.messages.saveSuccess);
    },

    loadRecorderInfo() {
      const saved = localStorage.getItem('nrs_recorderInfo');
      if (saved) {
        this.recorderInfo = JSON.parse(saved);
        // 如果有默认备注，设置到表单中
        if (this.recorderInfo.defaultRemarks && !this.formData.remarks) {
          this.formData.remarks = this.recorderInfo.defaultRemarks;
        }
      }
    },

    // 导出相关方法
    showExportDialog() {
      if (!this.recorderInfo.surveyId) {
        alert('请先设置问答编号！');
        return;
      }
      this.showExport = true;
      this.exportPassword = '';
    },

    closeExport() {
      this.showExport = false;
      this.exportPassword = '';
      this.isExporting = false;
    },

    async exportData() {
      if (!this.exportPassword) {
        alert('请输入导出密码！');
        return;
      }

      this.isExporting = true;

      try {
        const response = await fetch('/api/export-nrs-survey', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            surveyId: this.recorderInfo.surveyId,
            password: this.exportPassword,
            exportOptions: this.exportOptions
          })
        });

        if (response.ok) {
          // 处理文件下载
          const blob = await response.blob();
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = `NRS疼痛评估_${this.recorderInfo.surveyId}_${new Date().toISOString().split('T')[0]}.zip`;
          document.body.appendChild(a);
          a.click();
          window.URL.revokeObjectURL(url);
          document.body.removeChild(a);
          
          alert(nrsConfig.messages.exportSuccess);
          this.closeExport();
        } else {
          if (response.status === 401) {
            alert(nrsConfig.messages.passwordError);
          } else if (response.status === 404) {
            alert(nrsConfig.messages.noDataError);
          } else {
            alert(nrsConfig.messages.exportError);
          }
        }
      } catch (error) {
        console.error('导出错误:', error);
        alert(nrsConfig.messages.exportError);
      } finally {
        this.isExporting = false;
      }
    },

    // 评估相关方法
    submitAssessment() {
      const validation = validateNRSForm(this.formData);
      if (!validation.isValid) {
        alert('请完善以下信息：\n' + validation.errors.join('\n'));
        return;
      }

      // 计算评估结果
      this.result = calculateNRSAssessment(this.formData);
      this.showResult = true;

      // 滚动到顶部
      window.scrollTo({ top: 0, behavior: 'smooth' });
    },

    async saveToBackend() {
      if (!this.recorderInfo.surveyId || !this.recorderInfo.name || !this.recorderInfo.position) {
        alert(nrsConfig.messages.requiredFieldsError);
        return;
      }

      this.isSaving = true;

      try {
        // 1. 保存问卷数据到后台
        const response = await fetch('/api/save-nrs-survey', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            surveyId: this.recorderInfo.surveyId,
            recorderName: this.recorderInfo.name,
            recorderPosition: this.recorderInfo.position,
            recorderInstitution: this.recorderInfo.institution,
            recorderContact: this.recorderInfo.contact,
            ...this.formData,
            patientName: this.formData.patientName || "未填写",
            age: this.formData.age || 0,
            // 添加计算结果字段
            maxPainScore: this.result.maxPainScore,
            painLevel: this.result.painLevel,
            painLevelRange: this.result.painLevelRange,
            recommendations: this.result.recommendations,
            createdAt: new Date().toISOString()
          })
        });

        if (!response.ok) {
          const errorText = await response.text();
          throw new Error(errorText);
        }

        // 2. 生成评估报告内容
        const reportContent = this.generateNRSReport();

        // 3. 保存评估报告到@data/文件夹
        await this.saveFileToDataFolder(reportContent);

        alert('✅ 数据已成功保存到后台！\n\n📁 问卷数据：survey_data/\n📄 评估报告：@data/');

      } catch (error) {
        console.error('保存错误:', error);
        alert('❌ 保存失败，请检查网络连接或联系管理员！\n\n错误信息：' + error.message);
      } finally {
        this.isSaving = false;
      }
    },

    generateNRSReport() {
      const timestamp = new Date().toLocaleString('zh-CN');
      const recordTime = this.formData.recordTime ?
        new Date(this.formData.recordTime).toLocaleString('zh-CN') :
        timestamp;

      return `NRS疼痛评估结果报告
问答编号：${this.recorderInfo.surveyId}
生成时间：${timestamp}

=== 记录人信息 ===
记录人姓名：${this.recorderInfo.name}
记录人职务/身份：${this.recorderInfo.position}
所属机构：${this.recorderInfo.institution}
联系方式：${this.recorderInfo.contact}
记录时间：${recordTime}
备注：${this.formData.remarks || '无'}

=== 被评估人基本信息 ===
姓名：${this.formData.patientName}
年龄：${this.formData.age}岁
性别：${this.formData.gender === 'male' ? '男性' : '女性'}
诊断：${this.formData.diagnosis || '未填写'}
联系电话：${this.formData.phone || '未填写'}

=== 疼痛评分 ===
当前疼痛：${this.result.currentPain}/10
24小时最严重疼痛：${this.result.worstPain24h}/10
24小时最轻微疼痛：${this.result.leastPain24h}/10
24小时平均疼痛：${this.result.averagePain24h}/10
静息时疼痛：${this.result.restPain}/10
活动时疼痛：${this.result.activityPain}/10
功能影响评分：${this.result.functionalImpact}/10

=== 疼痛等级 ===
等级：${this.result.painLevel}（${this.result.painLevelRange}）
最高疼痛评分：${this.result.maxPainScore}/10

=== 疼痛特征 ===
疼痛部位：${this.formData.painLocation || '未填写'}
疼痛性质：${this.formData.painCharacter ? this.formData.painCharacter.join('、') : '未填写'}
疼痛持续时间：${this.formData.painDuration || '未填写'}
诱发因素：${this.formData.painTriggers || '未填写'}
缓解因素：${this.formData.painRelief || '未填写'}

=== 建议措施 ===
${this.result.recommendations ? this.result.recommendations.map((rec, index) => `${index + 1}. ${rec}`).join('\n') : '无'}

报告结束
`;
    },

    async saveFileToDataFolder(content) {
      // 通过API保存文件到@data/文件夹
      const filename = `NRS疼痛评估结果_${this.recorderInfo.surveyId}_${this.formData.patientName}_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.txt`;

      const response = await fetch(`${window.location.protocol}//${window.location.hostname}:13000/api/save-file`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          filename: filename,
          content: content,
          surveyId: this.recorderInfo.surveyId
        })
      });

      if (!response.ok) {
        throw new Error('保存评估报告失败');
      }
    },

    resetForm() {
      // 重置表单数据
      this.formData = {
        patientName: '',
        age: null,
        gender: '',
        diagnosis: '',
        phone: '',
        recordTime: '',
        remarks: this.recorderInfo.defaultRemarks || '',
        currentPain: null,
        worstPain24h: null,
        leastPain24h: null,
        averagePain24h: null,
        restPain: null,
        activityPain: null,
        functionalImpact: null,
        painLocation: '',
        painCharacter: [],
        painDuration: '',
        painTriggers: '',
        painRelief: ''
      };

      // 重新设置当前时间
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      this.formData.recordTime = `${year}-${month}-${day}T${hours}:${minutes}`;

      this.showResult = false;
      
      // 滚动到顶部
      window.scrollTo({ top: 0, behavior: 'smooth' });
    },

    // 辅助方法
    getPainCharacterLabels(characters) {
      const labels = {
        'sharp': '尖锐痛/刺痛',
        'dull': '钝痛/隐痛',
        'burning': '烧灼痛',
        'throbbing': '跳痛/搏动性痛',
        'cramping': '痉挛痛',
        'aching': '酸痛',
        'shooting': '放射痛',
        'tingling': '麻刺感'
      };
      return characters.map(char => labels[char] || char).join('、');
    },

    getPainDurationLabel(duration) {
      const labels = {
        'acute': '急性（＜1周）',
        'subacute': '亚急性（1-4周）',
        'chronic': '慢性（＞4周）'
      };
      return labels[duration] || duration;
    }
  }
}
</script>

<style scoped>
/* 基础样式 */
.nrs-survey {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  background: #f5f7fa;
  min-height: 100vh;
}

/* 头部样式 */
.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 30px;
  border-radius: 15px;
  margin-bottom: 30px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.header h1 {
  margin: 0 0 10px 0;
  font-size: 2.5em;
  font-weight: 700;
}

.subtitle {
  margin: 0 0 20px 0;
  font-size: 1.1em;
  opacity: 0.9;
}

.header-actions {
  display: flex;
  gap: 15px;
}

.home-btn, .settings-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 2px solid rgba(255, 255, 255, 0.3);
  color: white;
  padding: 10px 20px;
  border-radius: 25px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 0.9em;
  display: flex;
  align-items: center;
  gap: 8px;
}

.home-btn:hover, .settings-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateY(-2px);
}

/* 模态框样式 */
.settings-modal, .export-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.settings-content, .export-content {
  background: white;
  padding: 30px;
  border-radius: 15px;
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.settings-header, .export-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #f0f0f0;
}

.settings-header h2, .export-header h2 {
  margin: 0;
  color: #333;
  font-size: 1.5em;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: #333;
}


.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #333;
}

.required {
  color: #e74c3c;
}

.form-group input, .form-group textarea {
  width: 100%;
  padding: 12px;
  border: 2px solid #e1e8ed;
  border-radius: 8px;
  font-size: 1em;
  transition: border-color 0.3s ease;
  box-sizing: border-box;
}

.form-group input:focus, .form-group textarea:focus {
  outline: none;
  border-color: #667eea;
}

.field-hint {
  margin: 5px 0 0 0;
  font-size: 0.85em;
  color: #666;
  font-style: italic;
}

.settings-actions, .export-actions {
  display: flex;
  gap: 15px;
  justify-content: flex-end;
  margin-top: 25px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.save-settings-btn, .export-confirm-btn {
  background: #667eea;
  color: white;
  border: none;
  padding: 12px 25px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1em;
  transition: all 0.3s ease;
}

.save-settings-btn:hover, .export-confirm-btn:hover:not(:disabled) {
  background: #5a67d8;
  transform: translateY(-2px);
}

.export-confirm-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.cancel-btn {
  background: #6c757d;
  color: white;
  border: none;
  padding: 12px 25px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1em;
  transition: background 0.3s ease;
}

.cancel-btn:hover {
  background: #5a6268;
}

/* 问卷表单样式 */
.section {
  background: white;
  padding: 30px;
  margin-bottom: 25px;
  border-radius: 15px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.section h2 {
  margin: 0 0 25px 0;
  color: #333;
  font-size: 1.8em;
  border-bottom: 3px solid #667eea;
  padding-bottom: 15px;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.assessment-description {
  background: linear-gradient(135deg, #e8f2ff 0%, #f0f8ff 100%);
  padding: 20px;
  border-radius: 10px;
  margin-bottom: 20px;
  color: #2c5aa0;
  border-left: 5px solid #667eea;
  font-weight: 500;
}

.assessment-note {
  background: #fff3cd;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 25px;
  color: #856404;
  border-left: 4px solid #ffc107;
  font-style: italic;
}

.question-item {
  margin-bottom: 30px;
  padding: 25px;
  background: #fafbfc;
  border-radius: 12px;
  border: 2px solid #e1e8ed;
  transition: border-color 0.3s ease;
}

.question-item:hover {
  border-color: #667eea;
}

.question-item h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 1.2em;
  font-weight: 600;
}

.question-desc {
  margin: 0 0 20px 0;
  color: #666;
  font-style: italic;
  line-height: 1.5;
}

/* NRS评分量表样式 */
.nrs-scale {
  background: white;
  padding: 20px;
  border-radius: 10px;
  border: 2px solid #e1e8ed;
}

.nrs-labels {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  font-weight: 600;
  color: #333;
}

.nrs-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 5px;
}

.nrs-option {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  padding: 10px 5px;
  border-radius: 8px;
  transition: all 0.3s ease;
  min-width: 40px;
}

.nrs-option:hover {
  background: #f0f8ff;
}

.nrs-option input[type="radio"] {
  margin: 0 0 5px 0;
  transform: scale(1.2);
}

.nrs-number {
  font-weight: 600;
  font-size: 1.1em;
  color: #333;
}

.nrs-option input[type="radio"]:checked + .nrs-number {
  color: #667eea;
}

/* 单选和多选样式 */
.radio-group, .checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.radio-group label, .checkbox-group label {
  display: flex;
  align-items: flex-start;
  padding: 15px;
  border: 2px solid #e1e8ed;
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: white;
}

.radio-group label:hover, .checkbox-group label:hover {
  border-color: #667eea;
  background: #f8f9ff;
}

.radio-group input, .checkbox-group input {
  margin: 0 12px 0 0;
  transform: scale(1.2);
}

/* 提交按钮 */
.form-actions {
  text-align: center;
  margin-top: 30px;
}

.submit-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 15px 40px;
  border-radius: 25px;
  cursor: pointer;
  font-size: 1.1em;
  font-weight: 600;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.submit-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.submit-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
  box-shadow: none;
}

/* 结果页面样式 */
.result-section {
  background: white;
  padding: 30px;
  border-radius: 15px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 3px solid #667eea;
}

.result-header h2 {
  margin: 0;
  color: #333;
  font-size: 1.8em;
}

.result-actions {
  display: flex;
  gap: 15px;
}

.result-actions button {
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 0.9em;
  transition: all 0.3s ease;
}

.export-btn {
  background: #17a2b8;
  color: white;
}

.export-btn:hover {
  background: #138496;
}

.save-btn {
  background: #28a745;
  color: white;
}

.save-btn:hover:not(:disabled) {
  background: #218838;
}

.save-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.reset-btn {
  background: #6c757d;
  color: white;
}

.reset-btn:hover {
  background: #5a6268;
}

/* 疼痛等级卡片 */
.pain-level-card {
  background: white;
  padding: 25px;
  border-radius: 12px;
  border: 3px solid;
  margin-bottom: 25px;
  text-align: center;
}

.pain-level-card h3 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 1.3em;
}

.pain-level-info {
  margin-bottom: 15px;
}

.pain-level-name {
  font-size: 1.8em;
  font-weight: 700;
  margin-right: 10px;
}

.pain-level-range {
  font-size: 1.1em;
  color: #666;
}

.pain-level-desc {
  color: #555;
  line-height: 1.6;
  margin: 0;
}

/* 评分网格 */
.score-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
  margin-top: 15px;
}

.score-item {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.score-name {
  font-weight: 600;
  color: #333;
}

.score-value {
  font-size: 1.2em;
  font-weight: 700;
  color: #667eea;
}

/* 疼痛特征和相关因素 */
.pain-characteristics, .pain-factors {
  margin-bottom: 25px;
}

.pain-characteristics h4, .pain-factors h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 1.2em;
}

.characteristic-item, .factor-item {
  margin-bottom: 10px;
  padding: 10px 0;
}

.characteristic-item strong, .factor-item strong {
  color: #555;
  margin-right: 8px;
}

/* 建议措施和说明 */
.recommendations, .explanation {
  margin-bottom: 25px;
}

.recommendations h4, .explanation h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 1.2em;
}

.recommendations ul, .explanation ul {
  margin: 0;
  padding-left: 20px;
}

.recommendations li, .explanation li {
  margin-bottom: 8px;
  line-height: 1.6;
  color: #555;
}

/* 记录人信息显示 */
.recorder-info-display {
  margin-bottom: 30px;
}

.recorder-card {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 10px;
  border-left: 4px solid #667eea;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.recorder-main-info h3 {
  margin: 0 0 5px 0;
  color: #333;
}

.recorder-main-info p {
  margin: 5px 0;
  color: #666;
}

.recorder-actions {
  display: flex;
  gap: 10px;
}

.edit-recorder-btn, .export-btn {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.edit-recorder-btn {
  background: white;
  color: #333;
}

.export-btn {
  background: #28a745;
  color: white;
  border-color: #28a745;
}

.edit-recorder-btn:hover {
  background: #f8f9fa;
}

.export-btn:hover {
  background: #218838;
}


.export-info {
  background: #e8f2ff;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
  border-left: 4px solid #667eea;
}

.export-info p {
  margin: 5px 0;
  color: #2c5aa0;
}

.export-options {
  margin-top: 20px;
}

.export-options .form-group {
  margin-bottom: 10px;
}

.export-options label {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.export-options input[type="checkbox"] {
  margin-right: 8px;
  width: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .nrs-survey {
    padding: 10px;
  }
  
  .header {
    padding: 20px;
  }
  
  .header h1 {
    font-size: 2em;
  }
  
  .header-actions {
    flex-direction: column;
  }
  
  .form-grid {
    grid-template-columns: 1fr;
  }
  
  .nrs-options {
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .nrs-option {
    min-width: 35px;
  }
  
  .result-header {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }
  
  .recorder-card {
    flex-direction: column;
    text-align: center;
    gap: 15px;
  }
  
  .recorder-actions {
    justify-content: center;
  }
  
  .result-actions {
    justify-content: center;
  }
  
  .score-grid {
    grid-template-columns: 1fr;
  }
  
  .settings-content, .export-content {
    width: 95%;
    margin: 20px;
  }
}
</style>